import requests

from utils.logger import Logger


class RequestHandler:
    """HTTP请求处理类"""
    def __init__(self, base_url=None):
        self.base_url = base_url
        self.session = requests.Session()
        self.logger = Logger.get_logger()
    
    def send_request(self, method, url, **kwargs):
        """发送HTTP请求"""
        # 构建完整URL
        full_url = self.base_url + url if self.base_url else url
        
        # 记录请求信息
        self.logger.info(f"请求信息: {method} {full_url}")
        self.logger.info(f"请求头: {kwargs.get('headers')}")
        self.logger.info(f"请求参数: {kwargs.get('params')}")
        self.logger.info(f"请求体: {kwargs.get('json') or kwargs.get('data')}")
        
        try:
            # 发送请求
            response = self.session.request(method, full_url, **kwargs)
            
            # 记录响应信息
            self.logger.info(f"响应状态码: {response.status_code}")
            try:
                self.logger.info(f"响应内容: {response.json()}")
            except ValueError:
                self.logger.info(f"响应内容: {response.text[:500]}")  # 限制日志长度
            
            return response
        except Exception as e:
            self.logger.error(f"请求发生异常: {str(e)}")
            raise    